/**
 * 版本对比组件
 * 用于展示多个段落版本并进行对比选择
 */

import React, { useState } from 'react';
import { Card, Button, Space, Tag, Rate, Tooltip, Progress, message, Alert } from 'antd';
import {
  CheckCircleOutlined,
  ReloadOutlined,
  StarOutlined,
  FullscreenOutlined,
  FullscreenExitOutlined,
  ThunderboltOutlined,
} from '@ant-design/icons';
import { ParagraphVersion, ParagraphStrategy } from '@/types/brainstorm';
import './style.css';

interface VersionCompareProps {
  versions: ParagraphVersion[];
  selectedVersionIndex?: number;
  onSelectVersion: (index: number) => void;
  onRegenerateVersion?: (index: number) => void;
  onMixVersions?: (selections: any[]) => void;
}

export const VersionCompare: React.FC<VersionCompareProps> = ({
  versions,
  selectedVersionIndex = -1,
  onSelectVersion,
  onRegenerateVersion,
  onMixVersions,
}) => {
  const [fullscreen, setFullscreen] = useState(false);
  const [mixMode, setMixMode] = useState(false);
  const [mixSelections, setMixSelections] = useState<any[]>([]);

  // 策略标签配置
  const strategyLabels: Record<ParagraphStrategy, { text: string; color: string; desc: string }> =
    {
      concise: { text: '简洁风格', color: 'blue', desc: '简明扼要，直入主题' },
      detailed: { text: '详细风格', color: 'green', desc: '详细阐述，深入展开' },
      vivid: { text: '生动风格', color: 'orange', desc: '生动形象，富有感染力' },
      'data-driven': { text: '数据风格', color: 'purple', desc: '数据驱动，理性分析' },
      mixed: { text: '混合风格', color: 'cyan', desc: '多种风格混合' },
    };

  // 处理文本选择（混合模式）
  const handleTextSelection = (versionIndex: number) => {
    if (!mixMode) return;

    const selection = window.getSelection();
    if (!selection || !selection.toString().trim()) return;

    const text = selection.toString().trim();
    const range = selection.getRangeAt(0);

    setMixSelections([
      ...mixSelections,
      {
        versionIndex,
        text,
        range: [range.startOffset, range.endOffset],
      },
    ]);

    message.success(`已选择片段: ${text.substring(0, 20)}...`);
    selection.removeAllRanges();
  };

  // 应用混合
  const handleApplyMix = () => {
    if (mixSelections.length === 0) {
      message.warning('请先选择要混合的片段');
      return;
    }

    onMixVersions?.(mixSelections);
    setMixMode(false);
    setMixSelections([]);
  };

  // 计算综合评分
  const getOverallScore = (version: ParagraphVersion): number => {
    if (version.aiScore) return version.aiScore;

    const { relevance, readability, originality, coherence } = version.metrics;
    return Math.round((relevance + readability + originality + coherence) / 4);
  };

  return (
    <div className={`version-compare ${fullscreen ? 'fullscreen' : ''}`}>
      {/* 顶部操作栏 */}
      <div className="compare-header">
        <div className="header-left">
          <h3>版本对比</h3>
          <Tag color="blue">{versions.length} 个版本</Tag>
        </div>

        <Space>
          {/* 混合模式切换 */}
          {versions.length > 1 && (
            <Button
              type={mixMode ? 'primary' : 'default'}
              icon={<ThunderboltOutlined />}
              onClick={() => {
                setMixMode(!mixMode);
                if (mixMode) {
                  setMixSelections([]);
                }
              }}
            >
              {mixMode ? '取消混合' : '混合模式'}
            </Button>
          )}

          {/* 应用混合 */}
          {mixMode && mixSelections.length > 0 && (
            <Button type="primary" onClick={handleApplyMix}>
              生成混合版本 ({mixSelections.length})
            </Button>
          )}

          {/* 全屏切换 */}
          <Button
            icon={fullscreen ? <FullscreenExitOutlined /> : <FullscreenOutlined />}
            onClick={() => setFullscreen(!fullscreen)}
          >
            {fullscreen ? '退出全屏' : '全屏显示'}
          </Button>
        </Space>
      </div>

      {/* 混合模式提示 */}
      {mixMode && (
        <Alert
          message="混合模式已开启"
          description="在各个版本中选择您喜欢的文本片段，系统将基于您的选择生成新的混合版本"
          type="info"
          showIcon
          closable
          style={{ marginBottom: 16 }}
        />
      )}

      {/* 版本列表 */}
      <div className={`versions-grid versions-${versions.length}`}>
        {versions.map((version, index) => {
          const isSelected = selectedVersionIndex === index;
          const overallScore = getOverallScore(version);
          const strategyInfo = strategyLabels[version.strategy] || strategyLabels.concise;

          return (
            <Card
              key={index}
              className={`version-card ${isSelected ? 'selected' : ''} ${
                version.generating ? 'generating' : ''
              } ${version.error ? 'error' : ''}`}
              title={
                <div className="version-card-header">
                  <Space>
                    <Tag color={strategyInfo.color}>{strategyInfo.text}</Tag>
                    {version.generating && <Tag color="processing">生成中...</Tag>}
                    {isSelected && (
                      <Tag color="success" icon={<CheckCircleOutlined />}>
                        已选中
                      </Tag>
                    )}
                    {version.error && <Tag color="error">错误</Tag>}
                  </Space>
                  <Tooltip title={strategyInfo.desc}>
                    <span className="strategy-desc">{strategyInfo.desc}</span>
                  </Tooltip>
                </div>
              }
              extra={
                <Space>
                  {!version.generating && !version.error && (
                    <>
                      <Tooltip title={`综合评分: ${overallScore}`}>
                        <div className="score-display">
                          <Rate
                            disabled
                            allowHalf
                            value={overallScore / 20}
                            style={{ fontSize: 14 }}
                          />
                          <span className="score-text">{overallScore}</span>
                        </div>
                      </Tooltip>
                    </>
                  )}
                </Space>
              }
              actions={
                version.generating
                  ? []
                  : [
                      <Button
                        key="select"
                        type={isSelected ? 'primary' : 'default'}
                        icon={<CheckCircleOutlined />}
                        onClick={() => onSelectVersion(index)}
                        disabled={!!version.error}
                      >
                        {isSelected ? '已选中' : '选择'}
                      </Button>,
                      <Button
                        key="regenerate"
                        icon={<ReloadOutlined />}
                        onClick={() => onRegenerateVersion?.(index)}
                      >
                        重新生成
                      </Button>,
                      <Tooltip key="favorite" title="收藏版本">
                        <Button icon={<StarOutlined />} />
                      </Tooltip>,
                    ]
              }
            >
              {/* 生成中 */}
              {version.generating && (
                <div className="generating-placeholder">
                  <Progress type="circle" percent={75} status="active" size="small" />
                  <p>正在生成中...</p>
                </div>
              )}

              {/* 错误状态 */}
              {version.error && (
                <Alert
                  message="生成失败"
                  description={version.error}
                  type="error"
                  showIcon
                  style={{ marginBottom: 16 }}
                />
              )}

              {/* 正常内容展示 */}
              {!version.generating && !version.error && (
                <>
                  <div
                    className={`version-content ${mixMode ? 'selectable' : ''}`}
                    onMouseUp={() => handleTextSelection(index)}
                  >
                    <p>{version.content || '暂无内容'}</p>
                  </div>

                  {/* 评分指标 */}
                  <div className="version-metrics">
                    <div className="metric-row">
                      <div className="metric-item">
                        <span className="metric-label">字数</span>
                        <strong>{version.wordCount || version.content?.length || 0}</strong>
                      </div>
                      <div className="metric-item">
                        <span className="metric-label">相关性</span>
                        <Progress
                          percent={version.metrics.relevance}
                          size="small"
                          status="active"
                          showInfo={false}
                        />
                        <span className="metric-value">{version.metrics.relevance}/100</span>
                      </div>
                    </div>

                    <div className="metric-row">
                      <div className="metric-item">
                        <span className="metric-label">可读性</span>
                        <Progress
                          percent={version.metrics.readability}
                          size="small"
                          status="active"
                          showInfo={false}
                        />
                        <span className="metric-value">{version.metrics.readability}/100</span>
                      </div>
                      <div className="metric-item">
                        <span className="metric-label">原创性</span>
                        <Progress
                          percent={version.metrics.originality}
                          size="small"
                          status="active"
                          showInfo={false}
                        />
                        <span className="metric-value">{version.metrics.originality}%</span>
                      </div>
                    </div>

                    <div className="metric-row">
                      <div className="metric-item">
                        <span className="metric-label">连贯性</span>
                        <Progress
                          percent={version.metrics.coherence}
                          size="small"
                          status="active"
                          showInfo={false}
                        />
                        <span className="metric-value">{version.metrics.coherence}/100</span>
                      </div>
                    </div>
                  </div>

                  {/* 评分理由 */}
                  {version.scoreReason && (
                    <div className="score-reason">
                      <h4>评分理由</h4>
                      <p>{version.scoreReason}</p>
                    </div>
                  )}
                </>
              )}
            </Card>
          );
        })}
      </div>

      {/* 已选择的片段预览 */}
      {mixMode && mixSelections.length > 0 && (
        <div className="mix-preview">
          <h4>已选择片段</h4>
          <Space wrap>
            {mixSelections.map((sel, idx) => (
              <Tag
                key={idx}
                closable
                color={strategyLabels[versions[sel.versionIndex]?.strategy]?.color || 'default'}
                onClose={() => {
                  setMixSelections(mixSelections.filter((_, i) => i !== idx));
                }}
              >
                版本{sel.versionIndex + 1}: {sel.text.substring(0, 30)}
                {sel.text.length > 30 ? '...' : ''}
              </Tag>
            ))}
          </Space>
        </div>
      )}
    </div>
  );
};
